package com.example.exam.securityConfig;

import com.example.exam.pojo.User;
import com.example.exam.service.imp.UserRoleService;
import com.example.exam.service.imp.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user= userService.selectUserByUsername(s);
        if(user==null){
            throw  new UsernameNotFoundException("没有该用户");
        }
        Iterator<String> roles = userRoleService.selectRoleByUserId(user.getId()).iterator();
        Set<GrantedAuthority> grantedAuthorities= new HashSet<>();
        while(roles.hasNext()){
            grantedAuthorities.add(new SimpleGrantedAuthority((String)roles.next()));
        }

        UserDetails userDetails= new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),grantedAuthorities);
        return userDetails;
    }
}
